@file:Suppress("DEPRECATION")

package com.UKIT.airtickets.Service

import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.preference.PreferenceManager
import android.util.Log
import java.util.Locale

object LanguageManager {

    private const val TAG = "LanguageManager"

    fun changeLanguage(context: Context, languageCode: String) {
        val locale = Locale(languageCode)
        Locale.setDefault(locale)

        val resources = context.applicationContext.resources
        val configuration = Configuration(resources.configuration)
        configuration.setLocale(locale)

        val displayMetrics = resources.displayMetrics
        resources.updateConfiguration(configuration, displayMetrics)

        saveLanguageToCache(context, languageCode)
        Log.d(TAG, "Язык изменен на $languageCode")
    }

    fun saveLanguageToCache(context: Context, languageCode: String) {
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
        val editor = sharedPreferences.edit()
        editor.putString("Language", languageCode)
        editor.apply()
    }

    fun getSavedLanguageFromCache(context: Context): String? {
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
        return sharedPreferences.getString("Language", null)
    }

    fun applyLanguage(context: Context, languageCode: String) {
        val savedLanguage = getSavedLanguageFromCache(context)
        savedLanguage?.let {
            if (it != languageCode) {
                changeLanguage(context, languageCode)
            }
        }
    }

    fun isLanguageChanged(context: Context, languageCode: String): Boolean {
        val savedLanguage = getSavedLanguageFromCache(context)
        return savedLanguage != languageCode
    }

    fun attachBaseContext(context: Context): Context {
        val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)
        val languageCode = sharedPref.getString("Language", null)

        languageCode?.let { code ->
            val currentLocale = if (Build.VERSION.SDK_INT >= 24) {
                context.resources.configuration.locales[0]
            } else {
                context.resources.configuration.locale
            }

            if (currentLocale.language != code) {
                val locale = Locale(code)
                val config = Configuration(context.resources.configuration)
                Locale.setDefault(locale)
                config.setLocale(locale)
                return context.createConfigurationContext(config)
            }
        }

        return context
    }
}
